<template>
  <div class="timer-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="header-left">
            <el-button @click="$router.push('/dashboard')" icon="ArrowLeft" class="back-btn">
              返回
            </el-button>
          </div>
          <div class="header-center">
            <div class="page-title">
              <el-icon class="title-icon"><Timer /></el-icon>
              <h2>计时</h2>
            </div>
          </div>
          <div class="header-right">
            <div class="timer-status">
              <el-tag v-if="isRunning" type="success" :disable-transitions="true" class="status-tag">运行中</el-tag>
              <el-tag v-else type="warning" :disable-transitions="true" class="status-tag">已停止</el-tag>
            </div>
          </div>
        </div>
      </el-header>
      
      <el-main class="main">
        <el-card class="timer-card">
          <div class="timer-display">
            <div class="time-display">{{ formatTime(displayTime) }}</div>
            <div class="timer-controls">
              <el-button 
                v-if="!isRunning && !isPaused" 
                type="primary" 
                size="large"
                @click="startTimer"
                :icon="VideoPlay"
              >
                开始
              </el-button>
              <el-button 
                v-else-if="isPaused" 
                type="success" 
                size="large"
                @click="resumeTimer"
                :icon="VideoPlay"
              >
                继续
              </el-button>
              <el-button 
                v-else-if="isRunning" 
                type="warning" 
                size="large"
                @click="pauseTimer"
                :icon="VideoPause"
              >
                暂停
              </el-button>
              <el-button 
                type="danger" 
                size="large"
                @click="stopTimer"
                :icon="Close"
              >
                停止
              </el-button>
              <el-button 
                type="info" 
                size="large"
                @click="resetTimer"
                :icon="Refresh"
              >
                重置
              </el-button>
            </div>
          </div>
        </el-card>
        
        <el-card class="record-card">
          <template #header>
            <h4>记录管理</h4>
          </template>
          <div class="record-controls">
            <el-button 
              type="success" 
              @click="saveRecord"
              :loading="saving"
              :disabled="!hasRecordedTime"
              class="record-controls-btn"
            >
              保存记录
            </el-button>
            <el-button 
              type="info" 
              @click="loadTodayTotal"
              class="record-controls-btn"
            >
              查看今日总计
            </el-button>
          </div>
          <div v-if="todayTotal > 0" class="today-total">
            <span>今日总计：{{ formatTime(todayTotal) }}</span>
          </div>
        </el-card>
      </el-main>
    </el-container>
    
    <!-- 悬浮主题切换按钮 -->

  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
// import axios from 'axios'
// 新写法（自动适配环境）
import request from '../utils/request'
import dayjs from 'dayjs'
// import { VideoPlay, VideoPause, VideoStop, Refresh } from '@element-plus/icons-vue'
import { VideoPlay, VideoPause, CircleClose, Close, Refresh, Timer } from '@element-plus/icons-vue'

const isRunning = ref(false)
const isPaused = ref(false)
const displayTime = ref(0)
const recordedTime = ref(0)
const todayTotal = ref(0)
const saving = ref(false)
// 导入计时器服务
import timerService from '../utils/timerService'

let timerInstance = null

const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const hasRecordedTime = computed(() => recordedTime.value > 0)

const startTimer = () => {
  if (!isRunning.value && !isPaused.value) {
    // 使用计时器服务创建计时器
    timerInstance = timerService.createTimer({
      onUpdate: (elapsed) => {
        displayTime.value = elapsed
      },
      onStart: () => {
        isRunning.value = true
        isPaused.value = false
      },
      onPause: () => {
        isRunning.value = false
        isPaused.value = true
      },
      onResume: () => {
        isRunning.value = true
        isPaused.value = false
      },
      onStop: () => {
        isRunning.value = false
        isPaused.value = false
      }
    })
    
    timerInstance.start()
  }
}

const pauseTimer = () => {
  if (isRunning.value && timerInstance) {
    timerInstance.pause()
    // recordedTime.value = displayTime.value
  }
}

const resumeTimer = () => {
  if (isPaused.value && timerInstance) {
    timerInstance.resume()
  }
}

const stopTimer = () => {
  if (timerInstance) {
    timerInstance.stop()
    timerInstance = null
  }
  isRunning.value = false
  isPaused.value = false
  recordedTime.value = displayTime.value
  displayTime.value = 0
}

const resetTimer = () => {
  if (timerInstance) {
    timerInstance.stop()
    timerInstance = null
  }
  isRunning.value = false
  isPaused.value = false
  displayTime.value = 0
  recordedTime.value = 0
}

const saveRecord = async () => {
  if (recordedTime.value <= 0) {
    ElMessage.warning('没有可保存的记录')
    return
  }
  
  try {
    saving.value = true
    const today = dayjs().format('YYYY-MM-DD')
    await  request.post('/timer/record', {
      date: today,
      duration: recordedTime.value,
      type: 'timer'
    })
    ElMessage.success('记录保存成功')
    recordedTime.value = 0
    await loadTodayTotal()
  } catch (error) {
    console.error('保存记录失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const loadTodayTotal = async () => {
  try {
    const response = await  request.get('/timer/today/total')
    todayTotal.value = response.data.totalTime
  } catch (error) {
    console.error('获取今日总计失败:', error)
  }
}

onMounted(() => {
  loadTodayTotal()
})

onUnmounted(() => {
  if (timerInstance) {
    timerInstance.stop()
    timerInstance = null
  }
})
</script>

<style scoped>
.timer-page {
  min-height: 100vh;
   background-color: var(--bg-primary);
}

.header {
  background: var(--header-bg);
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.title-icon {
  font-size: 24px;
  color: #ffd700;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.back-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.timer-status {
  display: flex;
  align-items: center;
  gap: 16px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.status-tag {
  font-size: 14px;
  font-weight: 500;
  border: none;
  /* background: rgba(255, 255, 255, 0.2);
  color: white; */
}

.main {
  padding: 20px;
}

.timer-card {
  max-width: 600px;
  margin: 0 auto 20px;
}

.timer-display {
  text-align: center;
  padding: 20px;
}

.time-display {
  font-size: 48px;
  font-weight: bold;
  font-family: 'Courier New', monospace;
  color: #303133;
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.timer-controls {
  display: flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
}

.record-card {
  max-width: 600px;
  margin: 0 auto;
}

.record-card h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.record-controls {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 16px;
}

.today-total {
  text-align: center;
  padding: 12px;
  background-color: #f6ffed;
  border-radius: 6px;
  color: #52c41a;
  font-weight: 600;
}

/* 移动端适配 */
@media (max-width: 768px) {
/* 仅 5+ App 环境生效（通过标记类精准控制） */
html.app-5plus .header {
  padding-top: var(--status-bar-height);
height: calc(55px + var(--status-bar-height));
}
  .header-content {
      /* 保持横向排列，不换行 */
      flex-direction: row; 
      padding: 10px 0;
      gap: 6px; /* 进一步缩小间距 */
    }

    .date-navigation {
      order: 0; /* 恢复默认顺序，不放在最上面 */
      gap: 6px;
    }

    /* 可选：如果按钮文字太长，可只保留图标（按需选择） */
    .header-content .el-button span {
      display: none; /* 隐藏按钮文字，只显示图标 */
     }
  /* .header-content {
    flex-direction: column;
    gap: 10px;
    padding: 10px 0;
  }
  
  .date-navigation {
    order: -1;
  } */

   .el-button {
      font-size: 11px;
      border-radius: 15px;
   }

    .record-controls-btn
   {
      font-size: 13px;
     }
  .main {
    padding: 10px;
  }
  
  .time-display {
    font-size: 60px;
  }
  
  .timer-controls {
    flex-direction: row;
    gap: 10px;
    align-items: center;
  }
  
  .record-controls {
    flex-direction: row;
    align-items: center;
  }
}
</style> 